<template>
  <div>    
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="rolecard">
      <!-- 添加角色按钮部分 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addrole">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 添加角色弹出的对话框 -->
      <el-card class="addrolecard" v-show="isaddrole">
        <template #header>
          <div class="card-header">
            请填写新用户的信息
          </div>
        </template>
        <div class="text item">
          <el-form :model="addroleInfo" :rules="addrolerules" ref="addroleForm" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="addroleInfo.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="addroleInfo.roleDesc"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-button @click="addrolecancel">取消</el-button>
        <el-button @click="addroleconfirm">确认</el-button>
      </el-card>

      <!-- 编辑角色弹出的对话框 -->
      <el-card class="editrolecard" v-show="editroleVisible">
        <template #header>
          <div class="card-header">
            请修改角色信息
          </div>
        </template>
        <div class="text item">
          <el-form :model="editroleForm" :rules="editrolerules" ref="editroleForm" label-width="80px">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="editroleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
              <el-input v-model="editroleForm.roleDesc"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-button @click="editrolecancel">取消</el-button>
        <el-button @click="editroleconfirm">确认</el-button>
      </el-card>

      <!-- 分配角色权限弹出的对话框  -->
      <el-dialog
        title="提示"
        :visible.sync="setroledialogVisible"
        width="60%">
        <el-tree 
          :data="setroletreeInfo" 
          :props="treeProps" 
          show-checkbox
          :default-expand-all="true"
          node-key="id"
          :default-checked-keys="defaultarray"
          @close="setroleclose"
          ref="setroletree"
          >
        </el-tree>

        <span slot="footer" class="dialog-footer">
          <el-button @click="setroledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setroleconfirm">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 角色列表展示部分 -->
      <el-table :data="rolelist" border stripe >
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row v-for="(item,index) in scope.row.children" :key="item.id" :class="['bdbottom',index===0?'bdtop':'','vcenter']">
              <el-col :span="5">
                <el-tag class="setshow" closable @close="removeright(scope.row,item.id)">{{item.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>

              <el-col :span="19">
                <el-row v-for="(item2,index) in item.children" :key="item2.id" :class="['bdtop',index===0?'bdtopnone':'','vcenter']">
                  <el-col :span="6">
                    <el-tag class="setshow" type="success"  closable @close="removeright(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag  class="setshow2" v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeright(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>            
            <!-- {{scope.row}} -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template  slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editrole(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleterole(scope.row.id)">删除</el-button>
            <el-button size="mini" type="warning" icon="el-icon-setting" @click="setrole(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>  
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Rules",
  data(){
    return {
      rolelist: [],
      // 添加角色部分数据
      addroleInfo: {},
      isaddrole: false,
      addrolerules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
      },
      // 编辑角色对话框部分数据
      editroleVisible: false,
      editroleForm: {},
      editrolerules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 分配角色部分数据
      setroledialogVisible: false,
      setroletreeInfo: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defaultarray: [],
      roleid: null,
    }
  },
  created() {
    this.getrolelist();
  },
  methods: {
    // 获取整个角色列表
    async getrolelist(){
      const {data:res} = await this.$http.get("/roles");
      if(res.meta.status !== 200) return this.$message.error("获取角色列表失败")
      this.rolelist = res.data;
      // this.$message.success("获取角色列表成功");
      // console.log(this.rolelist);
    },

    // 增加角色相关代码
    addrole(){
      this.isaddrole = true;
    },
    addrolecancel(){
      this.isaddrole = false;
      this.$refs.addroleForm.resetFields();
    },
    async addroleconfirm(){
      this.isaddrole = false;
      // console.log(this.addroleInfo);
      const {data: res} = await this.$http.post("roles",this.addroleInfo);
      this.getrolelist();
      this.$refs.addroleForm.resetFields();
      // console.log(res);
    },

    // 编辑角色相关代码
    async editrole(id){
      const {data: res} =await this.$http.get("/roles/"+id);
      // console.log(res);
      this.editroleForm = res.data;
      // console.log(this.editroleForm);
      this.editroleVisible = true;
      // console.log(id);
    },
    editrolecancel(){
      this.editroleVisible = false;
      this.$refs.editroleForm.resetFields();
    },
    async editroleconfirm(){
      this.editroleVisible = false;
      const {data: res} = await this.$http.put("/roles/"+this.editroleForm.roleId,this.editroleForm);
      if(res.meta.status !== 200) return this.$message.error("更改角色信息失败")
      this.getrolelist();
      this.$message.success("更改角色信息成功")
      this.$refs.editroleForm.resetFields();
      // console.log(res);
    },

    // 删除角色相关代码
    async deleterole(id){
      // const {data: res} = await this.$http.delete("/roles/"+id);
      // if(res.meta.status !== 200) return this.$message.error("删除角色失败");
      // this.$message.success("删除角色成功")
      // this.getrolelist();

      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(res => {
          this.$http.delete("/roles/"+id).then(res=>{
             if(res.status !== 200) return this.$message.error("删除失败");
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getrolelist();
            // console.log(res);
          }).catch(err=>console.log(err));         
        })
        .catch((err) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      
    },

    // 分配角色相关代码

    getdeflist(node,arr){
      if(!node.children){
        return arr.push(node.id);
      }

      node.children.forEach(item=>{
        this.getdeflist(item,arr);
      })
    },
    async setrole(role){
      this.roleid = role.id;
      this.setroledialogVisible = true;
      const {data: res} = await this.$http.get("rights/tree");
      // console.log(res);
      this.setroletreeInfo = res.data;
      this.getdeflist(role,this.defaultarray);
      // console.log(this.defaultarray);
      // console.log(res.data);
    },
    setroleclose(){
      this.defaultarray = [];
    },
    async setroleconfirm(){
      const idarrays = [...this.$refs.setroletree.getCheckedKeys(),...this.$refs.setroletree.getHalfCheckedKeys()];
      // console.log(idarrays);
      const idstr = idarrays.join(",");
      // console.log(idstr);
      const {data: res} = await this.$http.post(`/roles/${this.roleid}/rights`,{
        rids: idstr
      });
      if(res.meta.status !== 200) return this.$message.error("分配角色失败");
      this.getrolelist();
      this.defaultarray = [];
      // console.log(res);
      this.setroledialogVisible = false;
    },
    removeright(role,rightid){
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(res => {
          this.$http.delete(`roles/${role.id}/rights/${rightid}`).then(res=>{
             if(res.data.meta.status !== 200) return this.$message.error("删除失败");
             role.children = res.data.data;
            // console.log();
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
          }).catch(err=>console.log(err));         
        })
        .catch((err) => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    }

  }
}
</script>

<style scpoed>
  .el-card{
    margin-top: 30px;
  }

  .rolecard{
    position: relative;
  }

  .el-table{
    margin-top: 20px;
  }

  .treedialog{
    width: 500px;
  }
  .setshow{
    margin: 8px 0px;
  }

  .setshow2{
    margin: 8px 5px
  }

  .bdtop{
    border-top: 1px solid #f6f6f6;
  }

  .bdbottom{
    border-bottom: 1px solid #f6f6f6;
  }

  .bdtopnone{
    border-top: none !important;
  }

  .vcenter{
    display: flex;
    align-items: center;
  }

  
</style>